package com.xbai.web.search.controller;

import com.xbai.entity.Page;
import com.xbai.search.feign.SkuFeign;
import com.xbai.search.pojo.SkuInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

/**
 * @author jxbai
 * @desc
 * @date 2021/2/2 0002
 */
@Controller
@RequestMapping(value = "/search")
@RequiredArgsConstructor
public class SkuController {

    private final SkuFeign skuFeign;

    @GetMapping("/list")
    public String search(@RequestParam(required = false) Map<String, String> searchMap, Model model) {
        //调用changgou-service-search微服务
        Map resultMap = skuFeign.search(searchMap);
        //搜索数据结果
        model.addAttribute("result", resultMap);
        //搜索条件
        model.addAttribute("searchMap", searchMap);
        // 请求地址
        String url = url(searchMap);
        model.addAttribute("url", url);

        //创建一个分页的对象  可以获取当前页 和总个记录数和显示的页码(以当前页为中心的5个页码)
        Page<SkuInfo> infoPage = new Page<SkuInfo>(
                Long.parseLong(resultMap.get("total").toString()),
                Integer.parseInt(resultMap.get("pageNum").toString()),
                Integer.parseInt(resultMap.get("pageSize").toString())
        );
        model.addAttribute("page",infoPage);

        return "search";
    }


    private String url(Map<String, String> searchMap) {
        String url = "/search/list";
        if (searchMap != null && searchMap.size() > 0) {
            url += "?";
            for (Map.Entry<String, String> entry : searchMap.entrySet()) {
                //如果是排序 则 跳过 拼接排序的地址 因为有数据
                if("sortField".equals(entry.getKey()) || "sortRule".equals(entry.getKey()) || "pageNum".equals(entry.getKey())) {
                    continue;
                }
                url += entry.getKey() + "=" + entry.getValue() + "&";
            }
            url = url.substring(0, url.length() - 1);
        }
        return url;
    }

}
